package _5thread;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Description:
 * @Author wangzhen
 * @Date 2022-06-16 21:56
 **/
class Student{
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class AtomicReferenceTest {


    static AtomicStampedReference<Student> zhangsan=new AtomicStampedReference(new Student("张三",15),0);
    public static void main(String[] args) throws Exception {



        new Thread(()->{
            Student reference = zhangsan.getReference();
            System.out.println(Thread.currentThread().getName()+"准备修改:"+reference);

            reference.setAge(16);
            int version;
            do{
                version = zhangsan.getStamp();

            }while (!zhangsan.attemptStamp(reference,version));

            System.out.println(Thread.currentThread().getName()+"操作成功:"+zhangsan.getReference());

        }).start();


        new Thread(()->{
            Student reference = zhangsan.getReference();
            System.out.println(Thread.currentThread().getName()+"准备修改:"+reference);
            reference.setAge(17);

            int version;
            do{
                version = zhangsan.getStamp();

            }while (!zhangsan.attemptStamp(reference,version));

            System.out.println(Thread.currentThread().getName()+"操作成功:"+zhangsan.getReference());

        }).start();

    }
}
